<?php
/**
 * 账单模块
 **/
namespace Xijie\Controller;
use Think\Controller;

class CostlogController extends Controller {
	//应用ID
	protected $development_id = 0;

	public function __construct() {
        parent::__construct();
		//判断是否登陆
		if(session('user_id')){ //已登陆

		}else{ //未登陆，跳转道登陆界面
			$this->redirect("index/index");
		}
		
		$this->development_id = session('development_id');
    }
	
	/**
	 * 费用明细
	 **/
	public function index(){
		if(IS_GET){
			$ajax = I('ajax') ? (int)I('ajax') : 0;
			$page = I('page') ? (int)I('page') : 1;

			//按业主名称模糊搜索
			$roomnumber = I('get.room_number') ? trim(I('get.room_number')) : '';
			if(!empty($roomnumber)){
				$param['room_number'] = $where['orders.roomnumber'] = $roomnumber;
			}
			
			//账单日期
			$costlog_times = I('get.qorder_type', date('m'));
			$costlog_years = I('get.qorder_year', date('Y'));
			if(!empty($costlog_times)){
				$param['qorder_type'] = $costlog_times;
				$param['qorder_year'] = $costlog_years;
				$where['orders.month'] = $costlog_years .'-'. str_pad($costlog_times, 2, '0', STR_PAD_LEFT);
			}
			
			//账单类型
			$order_type = I('get.order_type', 0);
			if(!empty($order_type)){
				$param['order_type'] = $where['orders.order_type'] = $order_type;
			}
			//账单状态
			$status = I('get.status');
			if($status != '' && $status != 'all'){
				$param['status'] = $where['orders.status'] = $status;
			}

			//获取总数
			$count = D('Costlog')->getCostLogListCount($where);
			//获取列表
			$list = D('Costlog')->getCostLogList($page, $where, 'orders.roomnumber/1 asc, orders.month asc');
			//echo D('Costlog')->_sql();
			
			$this->assign('list', $list);
			$this->assign('count', $count);
			$this->assign('page', $page);

			if(count($param)){
				$this->assign('param', json_encode($param));
			}
			if($ajax){
				$this->display('list', 'utf-8', 'html');
			}else{
				$this->display();
			}
		}else{
			ini_set('max_execution_time', '0'); //设置不超时
			//账单生成，生成当前时间下一个月的账单
			$year = I('post.year', date('Y')); //默认当前年
			$month = I('post.month', date('m')); //默认当前月
			//费用月份
			$order_month = $year. '-' . str_pad($month, 2, '0', STR_PAD_LEFT);
			//费用类型
			$order_type = I('istype', 1); //1:固定费用 2：常规费用
			$cover = I('post.cover', 0); //1：确定覆盖 0：不覆盖
			//获取当前时间
			$time = strtotime($order_month. '-01 00:00:00'); // 账单月的第一天
			//按条件判断合同的有效性，再生成账单。 当前时间必须要小于合同终止时间1个月,且账单月必须要小于等于合同终止月
			//固定账单
			if($order_type == 1){
				$list = D('Member')->getMemberListToOrder(array(
					'member.etime' => array('gt', $time),
					'member.btime' => array('elt', $time),
					'member.istype' => 1, //长租
					'member.visible' => 1,
					//'member.room_number' => '1123'
				));
				
				//判断是否存在合同
				if(is_array($list) && count($list)){
					$event = array();
					foreach($list as $k=>$ls){
						//echo $ls['btime'] . "<br />";
						//0. 获取租用时间
						$zmonth = getMonthNum(date('Y-m-d', $ls['btime']), date('Y-m-d', $ls['etime']));
						//echo "租用时间: ". $zmonth . "<br />";
						//1. 计算签约时间到账单月时间的月数
						$xmonth = $this->getMonthNum(date('Y-m-d', $ls['btime']), $order_month); //abs(date('m', $ls['btime']) - $month);
						//echo "已使用时间: ". $xmonth . "<br />";
						//重新计算时间 2017-11-07 23:41
						//2. 获取账单开始时间
						$begin_time = c_strtotime($ls['btime'], $xmonth, "+", false);
						//3. 计算结束时间 + 1month - 1day
						$end_times = c_strtotime($ls['btime'], ($xmonth+1), "+", true);
						//判断用户的合同开始月是否与账单月相同
						if(date('Y-m-d', $ls['btime']) >= date('Y-m-d', $begin_time)){
							//echo '-----1-----'. $ls['room_number'];
							//账单月与合同签约月相同或者小月签约月，不生成账单
						}else if($begin_time >= $ls['etime']){
							echo '-----2----- 合同已过期';
						}else if(strtotime(date('Y-m-d', $end_times) . ' 00:00:00') > strtotime(date('Y-m-d', $ls['etime']) . ' 00:00:00')){ //账单结束时间 > 合同截止时间，不生成账单
							//echo $begin_time. ' --- '. $end_times;
						}else{
							//判断是否已经存在账单 getCostInfoByWhere
							$costinfo = D('Costlog')->getCostInfoByWhere(array('month' => $order_month, 'roomnumber' => $ls['room_number'], 'order_type' => $order_type));
							//if(D('Costlog')->getCostLogListCount(array('month' => $order_month, 'roomnumber' => $ls['room_number'], 'order_type' => $order_type))){
							if(count($costinfo) && $costinfo['status'] == 1){
								//账单已存在，不生成账单
							}else{
								$flag = true;
								if(count($costinfo)){ 
									if($cover == 1){ // 覆盖
										//删除原有账单
										D('Costlog')->deleteCostInfo(array(
											'month' => $order_month,
											'roomnumber' => $ls['room_number'],
											'order_type' => $order_type
										));
									}else{
										$flag = false;
									}
								}
								//判断是否添加日志
								if($flag){
									//1. 查询固定费用
									$roomInfo = D('Room')->getRoomInfoByNumber($ls['room_number']);
									if($ls['rent'] <= 0){
										//设置合同金额为房间金额
										$ls['rent'] = $roomInfo['rent'];
									}
									if($ls['property'] <= 0){
										$ls['property'] = $roomInfo['property'];
									}
									//获取活动
									$event = D('Eventtype')->getMemberEventTypeByBtime(date('Y-m-d', $ls['btime']), date('Y-m-d', $ls['etime']), $roomInfo['root_type'], $ls['contract']);
									//计算
									$rent = $property = $other = $discount = 0;
									if(is_array($event) && count($event)){ //计算开始优惠月
										//计算是否达到优惠月 ，是否使用合同结束时间或者是账单月时间
										// 2017-11-07
										$smonth = $zmonth - $xmonth; //已租用月数
										if($event['rent_count'] && $smonth <= $event['rent_count']){
											$newrent = $ls['rent'] * $event['rent_multiple'];
											//如果为全免，那么享受的金额为 0
											$rent = $newrent ? $ls['rent'] - $newrent : $ls['rent'];
										}
										
										if($event['property_count'] == -1 || ($event['property_count'] && $smonth <= $event['property_count'])){
											$newproperty = $ls['property'] * $event['property_multiple'];
											//如果为全免，那么享受金额为 0
											$property = $newproperty ? $ls['property'] - $newproperty : $ls['property'];
										}
										
										/* 2017-11-07 以前
										$rentFalg = false;
										if($event['rent_count'] >= 1){
											if($event['rent_count'] == 1){
												//月租 费用结束时间 + 优惠月数 >= 合同终止时间
												$lastBeginTime = $end_times;
												$rentFalg = true;
											}else{
												//月租 费用结束时间 + 优惠月数 >= 合同终止时间
												$lastBeginTime = strtotime("+". $event['rent_count']. " month", $end_times);
											}
										}else{
											$lastBeginTime = 0;
										}
										
										$propertyFalg = false;
										if($event['property_count'] >= 1){
											if($event['property_count'] == 1){
												$lastPropertyTime = $end_times;
												$propertyFalg = true;
											}else{
												$lastPropertyTime = strtotime("+". $event['property_count']. " month", $end_times);
											}
										}else{
											$lastPropertyTime = 0;
										}
										
										//计算享受的月租减免金额 是否是>=
										if($rentFalg || ($lastBeginTime && date('Y-m-d', $lastBeginTime) > date('Y-m-d', $ls['etime']))){
											$newrent = $ls['rent'] * $event['rent_multiple'];
											//如果为全免，那么享受的金额为 0
											$rent = $newrent ? $ls['rent'] - $newrent : $ls['rent'];
										}
										
										//计算享受的物业减免金额 是否是>=
										if($event['property_count'] == -1 || $propertyFalg || ($lastPropertyTime && date('Y-m-d', $lastPropertyTime) > date('Y-m-d', $ls['etime']))){ //租期内享受
											$newproperty = $ls['property'] * $event['property_multiple'];
											//如果为全免，那么享受金额为 0
											$property = $newproperty ? $ls['property'] - $newproperty : $ls['property'];
										}
										*/
										//计算享受总金额
										$discount = $rent + $property;
										//活动水电补助
										$other = $event['other'];
									}else{
										$event = array(
											'typeid' => 0,
											'type_title' => '',
										);
									}
									//是否添加
									$isAdd = true;
									//组装固定费用
									if($end_times <= $ls['leaving_time'] && $end_times <= $ls['property_time']){
										//判断用户费用截止时间是否大于当前时间
										$status = 1;
										$ls['rent'] = $ls['property'] = $ls['discount'] = $total = $discount = 0;
										//$total = $ls['rent'] + $ls['property'] - $discount;
										$unpaid = 0;
									}else if($end_times <= $ls['leaving_time'] && $end_times > $ls['property_time']){
										$status = -1;
										$total = $unpaid = $ls['property'] - $property;
										$ls['discount'] = 0;
										$discount = $property;
										$ls['rent'] = 0;
									}else if($end_times > $ls['leaving_time'] && $end_times <= $ls['property_time']){
										$status = -1;
										$unpaid = $total = $ls['rent'] - $rent + $ls['discount'];
										$discount = $rent;
										$ls['property'] = 0;
									}else{
										$total = $ls['rent'] + $ls['property'] + $ls['discount'];
										//计算特殊优惠
										$total = $total <= 0 ? 0 : $total;
										$status = -1;
										$unpaid = 0;
									}
									//计算总额
									$account = $total - $discount;
									if($account <= 0){
										$status = 1;
										$account = 0;
									}
									//数据
									$rentData = array(
										'order_type' => 1,
										'order_sn' => 'MMGY_'. date('YmdHis') . '_'. $k,
										'roomnumber' => $ls['room_number'],
										'contract' => $ls['contract'],
										'month' => $order_month,
										'member_nick' => $ls['member_nick'],
										'rent' => $ls['rent'],
										'property' => $ls['property'],
										'eventtype_id' => $event['typeid'],
										'eventtype_title' => $event['type_title'],
										'eventtype_remark' => empty($event['remark']) ? '' : $event['remark'],
										'total' => $total,
										'account' => $account, //应缴 ＝ 应缴 + 特殊优惠
										'discount' => $discount, //优惠
										'other' => $ls['discount'], //特殊优惠
										'unpaid' => $unpaid, //未结清
										'status' => $status,
										'ordertime' => time(),
										'lastcalltime' => date('Y-m-d', $ls['leaving_time']),
										'begin_time' => $begin_time,
										'end_time' => $end_times
									);
									
									if(count($rentData) && is_array($rentData) && $isAdd){
										//保存账单
										D('Costlog')->addCostInfo($rentData);
									}
								}
								//添加费用记录
								unset($event);
							}
						}
					}
					echo 1;
				}else{
					echo 2;
				}
			}
			//日常费用账单
			else{
				$list = D('Member')->getMemberListToOrder(array(
					'member.istype' => 1, //长租
					'member.visible' => 1,
					//'member.room_number' => '1103'
				));
				
				//判断是否存在合同
				if(is_array($list) && count($list)){
					$event = array();
					//开始遍历
					foreach($list as $k=>$ls){
						//判断是否已经存在账单 getCostInfoByWhere
						$costinfo = D('Costlog')->getCostInfoByWhere(array('month' => $order_month, 'roomnumber' => $ls['room_number'], 'order_type' => $order_type));
						if(count($costinfo) && $costinfo['status'] == 1){
							//账单已存在，不生成账单
						}else if(date('Y-m', $ls['btime']) >= $order_month)){
							//签约月必须小于账单月
						}else{
							$flag = true;
							if(count($costinfo)){ 
								if($cover == 1){ // 覆盖
									//删除原有账单
									D('Costlog')->deleteCostInfo(array(
										'month' => $order_month,
										'roomnumber' => $ls['room_number'],
										'order_type' => $order_type
									));
									//删除订单月用户附属信息
									D('MemberProfile')->deleteMemberProfileInfoByMaxId($ls['room_number'], $ls['member_id'], $order_month);
								}else{
									$flag = false;
								}
							}
							//判断是否添加日志
							if($flag){
								//查询房间信息
								$roomInfo = D('Room')->getRoomInfoByNumber($ls['room_number']);
								//获取活动
								$event = D('Eventtype')->getMemberEventTypeByBtime(date('Y-m-d', $ls['btime']), date('Y-m-d', $ls['etime']), $roomInfo['root_type'], $ls['contract']);
								//计算
								$other = 0;
								if(is_array($event) && count($event)){ //计算开始优惠月
									//活动水电补助
									$other = $event['other'];
								}else{
									$event = array(
										'typeid' => 0,
										'type_title' => '',
									);
								}
								//组装日常费用
								$info = D('Hydropower')->getHydropowerInfoByRoomId($ls['room_number'], $order_month);
								//初始值
								$rates1 = $rates2 = $rates3 = 0;
								//日程账单状态统一为未审核
								$status = -1;
								if(count($info)){
									//获取上月止数
									/*
									$memberprofile = D('MemberProfile')->getMemberProfileInfoByMaxId($ls['room_number'], $ls['member_id'], $order_month);
									if(count($memberprofile)){
										$water = $memberprofile['water'];
										$electric = $memberprofile['electric'];
										$gas = $memberprofile['gas'];
									}else{
										//需要判断是否存在后几月的记录
										$isCount = D('MemberProfile')->getMemberProfileCountByMaxId($ls['room_number'], $ls['member_id'], $order_month);
										if($isCount){ //跳月收取了费用状态直接修改为1
											$memberprofile = D('MemberProfile')->getMemberProfileInfoByMaxIdT($ls['room_number'], $ls['member_id']);
											$water = $memberprofile['water'];
											$electric = $memberprofile['electric'];
											$gas = $memberprofile['gas'];
											//直接修改状态为1
											$status = 1;
										}else{
											$water = $ls['eqment_1'];
											$electric = $ls['eqment_2'];
											$gas = $ls['eqment_3'];
										}
									}
									*/
									
									//如果上月度数 > 新合同数，那么以新合同数为上月起数，反之依然
									$water = $info['before_water'] > $info['contract_water'] ? $info['before_water'] : $info['contract_water'];
									$electric = $info['before_electric'] > $info['contract_electric'] ? $info['before_electric'] : $info['contract_electric'];
									$gas = $info['before_gas'] > $info['contract_gas'] ? $info['before_gas'] : $info['contract_gas'];
									//开始计算费用
									$rates1 = ($info['water'] - $water) * $info['water_price'];
									$rates2 = ($info['electric'] - $electric) * $info['electric_price'];
									$rates3 = ($info['gas'] - $gas) * $info['gas_price'];
									//判断金额是否大于0
									$rates1 = $rates1 < 0 ? 0 : $rates1;
									$rates2 = $rates2 < 0 ? 0 : $rates2;
									$rates3 = $rates3 < 0 ? 0 : $rates3;
									
									$total = $rates1 + $rates2 + $rates3;
									$account = $total - $other;
									if($account <= 0){
										$account = 0;
										$status = 1;
									}
									
									//组装临时费用
									$rentData = array(
										'order_type' => 2,
										'order_sn' => 'MMGY_'. date('YmdHis') . '_'. $k,
										'roomnumber' => $ls['room_number'],
										'contract' => $ls['contract'],
										'month' => $order_month,
										'member_nick' => $ls['member_nick'],
										'rent' => 0,
										'property' => 0,
										'eventtype_id' => $event['typeid'],
										'eventtype_title' => $event['type_title'],
										'eventtype_remark' => empty($event['remark']) ? '' : $event['remark'],
										'rates1' => $rates1,
										'rates2' => $rates2,
										'rates3' => $rates3,
										'total' => $total,
										'account' => $account < 0 ? 0 : $account, //应缴
										'discount' => $other, //优惠
										'unpaid' => $account, //未结清金额
										'status' => $status,
										'ordertime' => time(),
										'lastcalltime' => date('Y-m-d', $ls['property_time']),
										'begin_time' => '',
										'end_time' => ''
									);
								}else{
									$total = $account = $other = 0;
									$rentData = array();
								}
								
								if(count($rentData) && is_array($rentData)){
									//保存账单
									$row = D('Costlog')->addCostInfo($rentData);
									if($row !== false){
										//保存当月抄表止数
										D('MemberProfile')->addMemberProfileInfo(array(
											'roomnumber' => $ls['room_number'],
											'userid' => $ls['member_id'],
											'month' => $order_month,
											'water' => $info['water'],
											'electric' => $info['electric'],
											'gas' => $info['gas'],
											'createtime' => time()
										));
									}
								}
							}
							//添加费用记录
							unset($event);
						}
					}
					echo 1;
				}else{
					echo 2;
				}	
			}	
		}
	}
	
	/**
	 * 费用催缴
	 **/
	public function call(){
		if(IS_GET){
			$ajax = I('ajax') ? (int)I('ajax') : 0;
			$page = I('page') ? (int)I('page') : 1;

			//按业主名称模糊搜索
			$roomnumber = I('get.room_number') ? trim(I('get.room_number')) : '';
			if(!empty($roomnumber)){
				$param['room_number'] = $where['orders.roomnumber'] = $roomnumber;
			}
			
			//账单日期
			$costlog_times = I('get.qorder_type', '');
			$costlog_years = I('get.qorder_year', date('Y'));
			
			if(!empty($costlog_times)){
				$param['qorder_type'] = $where['orders.month'] = $costlog_years .'-'. str_pad($costlog_times, 2, '0', STR_PAD_LEFT);
			}
			
			//账单类型
			$order_type = I('get.order_type', 0);
			if(!empty($order_type)){
				$param['order_type'] = $where['orders.order_type'] = $order_type;
			}
			//账单状态
			$param['status'] = $where['orders.status'] = 0;
			//上一次费用截止时间
			$lasttime = I('lasttime', 0);
			if(!empty($lasttime)){
				$param['lasttime'] = $where['orders.lastcalltime'] = $lasttime;
			}
			//获取总数
			$count = D('Costlog')->getCostLogListCount($where);
			//获取列表
			$list = D('Costlog')->getCostLogList($page, $where, 'order_id desc');

			$this->assign('list', $list);
			$this->assign('count', $count);
			$this->assign('page', $page);

			if(count($param)){
				$this->assign('param', json_encode($param));
			}
			if($ajax){
				$this->display('call_list', 'utf-8', 'html');
			}else{
				$this->display();
			}
		}else{
			//催缴费用
			$costlog_id = I('post.costlog_id', 0);
			//获取账单详情
			$costinfo = D('Costlog')->getCostInfoByWhere(array(
				'order_id' => $costlog_id
			));
			//判断是否存在账单
			if(is_array($costinfo) && count($costinfo)){
				//获取用户的电话号码
				$uinfo = D('Member')->getMemberInfoByContractArray($costinfo['contract']);
				if(is_array($uinfo) && count($uinfo)){
					$flag = sendSMSMessage($uinfo['member_phone'], 0, $uinfo['member_nick'], '',$uinfo['room_number'], $costinfo['lastcalltime'], 1);
					if($flag){
						$row = D('Costlog')->editCostLogInfo(array(
							'order_id' => $costlog_id
						), array(
							'cjcount' => array('exp', 'cjcount + 1'),
							'cjtime' => time()
						));

						if($row !== false){
							echo 1;
						}else{
							echo 0;
						}
					}else{
						echo 0;
					}
				}
			}else{
				echo 0;
			}
			// 
		}
	}

	//批量催缴
	public function allcall(){
		if(IS_POST){
			//催缴费用
			$costlog_id = I('post.costlog_id', 0);
			//获取账单详情
			$costlist = D('Costlog')->getCostAllListByWhere(array(
				'order_id' => array('in', rtrim($costlog_id, ','))
			));
			//判断是否存在账单
			if(is_array($costlist) && count($costlist)){
				foreach($costlist as $costinfo){
					//获取用户的电话号码
					$uinfo = D('Member')->getMemberInfoByContractArray($costinfo['contract']);
					if(is_array($uinfo) && count($uinfo)){
						$flag = sendSMSMessage($uinfo['member_phone'], 0, $uinfo['member_nick'], '',$uinfo['room_number'], $costinfo['lastcalltime'], 1);
						if($flag){
							$row = D('Costlog')->editCostLogInfo(array(
								'order_id' => $costlog_id
							), array(
								'cjcount' => array('exp', 'cjcount + 1'),
								'cjtime' => time()
							));
						}
					}
				}

				echo 1;
			}else{
				echo 0;
			}
		}
	}

	/**
	 * 修改状态
	 **/
	public function edit(){
		$orderid = I('post.orderid', 0);
		$status = I('post.status', 0);
		$row = D('Costlog')->editCostLogInfo(array(
			'order_id' => $orderid,
		), array(
			'status' => $status
		));

		if($row !== false){
			echo 1;
		}else{
			echo 0;
		}
	}

	/**
	 * 批量修改状态
	 *
	 **/
	public function report(){
		$ids = I('post.ids', '');
		$status = I('post.status', 0); //账单状态 -1: 未审核 0：未缴费 1：已缴费 2：无效
		if(!empty($ids)){
			//查询账单信息
			$orderinfo = D('Costlog')->getCostLogInfo(array(
				'order_id' => array('in', rtrim($ids, ','))
			));
			//判断订单是否存在
			if(count($orderinfo)){
				foreach($orderinfo as $order){
					if($order['order_type'] == 1 && $status != 2){
						//判断是否存在优惠
						$uinfo = D('Member')->getMemberInfoByContractArray($order['contract']);
						if(($order['rent'] + $order['property']) == $order['discount']){
							D('Member')->editMemberRentTimeAndPtime(array(
								'member_id' => $uinfo['member_id'],
								'leaving_time' => array('elt', $order['end_time'])
							), array(
								'checkin_time' => $uinfo['checkin_time'],
								'leaving_time' => $order['end_time']
							));
							
							if($uinfo['property_time'] < $order['end_time']){
								//修改时间
								D('Member')->editMemberRentTimeAndPtime(array(
									'member_id' => $uinfo['member_id'],
									'property_time' => array('elt', $uinfo['property_time'])
								), array(
									'property_time' => $order['end_time']
								));
							}
						}
						
						if($order['rent'] == $order['discount']){
							D('Member')->editMemberRentTimeAndPtime(array(
								'member_id' => $uinfo['member_id'],
								'leaving_time' => array('elt', $order['end_time'])
							), array(
								'checkin_time' => $uinfo['checkin_time'],
								'leaving_time' => $order['end_time']
							));
						}
						
						if($order['property'] == $order['discount'] && $uinfo['property_time'] < $order['end_time']){
							//修改时间
							D('Member')->editMemberRentTimeAndPtime(array(
								'member_id' => $uinfo['member_id'],
								'property_time' => array('elt', $uinfo['property_time'])
							), array(
								'property_time' => $order['end_time']
							));
						}
					}
				}
			}
			
			//修改状态
			$row = D('Costlog')->editCostLogInfo(array(
				'order_id' => array('in', rtrim($ids, ',')),
				'status' => array('NEQ', 1)
			), array(
				'status' => $status
			));

			if($row !== false){
				echo 1;
			}else{
				echo 0;
			}
		}else{
			echo 0;
		}
	}

	/**
	 * 数字现金转中文大写
	 *
	 **/
	private function _cny_map_unit($list,$units) { 
	    $ul = count($units); 
	    $xs = array(); 
	    foreach (array_reverse($list) as $x) { 
	        $l = count($xs); 
	        if ($x!="0" || !($l%4)){
				$n = ($x=='0'?'':$x).($units[($l-1)%$ul]); 
	        }else{
				$n = is_numeric($xs[0][0]) ? $x : '';
			}
			
	        array_unshift($xs,$n); 
	    } 
		
	    return $xs; 
	}

	private function cny($ns) { 
	    static 	$cnums = array("零","壹","贰","叁","肆","伍","陆","柒","捌","玖"), 
	        	$cnyunits = array("圆","角","分"), 
	        	$grees = array("拾","佰","仟","万","拾","佰","仟","亿"); 
	    list($ns1,$ns2) = explode(".",$ns,2); 
	    $ns2 = array_filter(array($ns2[1],$ns2[0])); 
	    $ret = array_merge($ns2,array(implode("", $this->_cny_map_unit(str_split($ns1),$grees)),"")); 
	    $ret = implode("",array_reverse($this->_cny_map_unit($ret,$cnyunits))); 
	    $string = str_replace(array_keys($cnums),$cnums,$ret);
		//整数后面添加"整"
		if(strpos($string, '分') > 0){
			return $string;
		}else{
			return $string.'整';
		}
	}

	/**
	 * 获取享受的活动规则
	 **/
	private function getEventInfo($btime, $etime){
		$btime = strtotime($btime.' 00:00:00');
		$etime = strtotime($etime.' 23:59:59');
		//开始获取活动信息
		$eventlist = D('Eventtype')->getEventInfoByWhere(array(
			'type_btime' => array('elt', $btime),
			'type_status' => 1
		));
		
		//判断是否有活动
		if(count($eventlist)){
			//计算合同签约时间
			$month = getMonthNum(date('Y-m-d', $btime), date('Y-m-d', $etime));
			//开始遍历规则
			foreach($eventlist as $ls){
				//获取活动规则
				$eventattr = D('Eventtype')->getEventTypeAttrByEventId($ls['typeid']);
				//判断是否存在规则
				if(count($eventattr)){
					$attrList['type_title'] = $ls['type_title'];
					$attrList['btime'] = $ls['type_btime'];
					$attrList['etime'] = $ls['type_etime'];
					$attrList['admin_nick'] = $ls['admin_nick'];
					$attrList['type_status'] = $ls['type_status'];
					$attrList['typeid'] = $ls['typeid'];

					//计算参与的最大活动规则
					foreach($eventattr as $attr){
						if($month < $attr['attr_month']){ //小于
							$attrList['attr'] = $attr;
						}else if($month == $attr['attr_month']){ //等于
							$attrList['attr'] = $attr;
						}else if($month > $attr['attr_month']){ //大于
							$attrList['attr'] = $attr;
						}
					}
				}
			}
		}

		return $attrList;
	}

	public function explodes(){
		//按业主名称模糊搜索
		$roomnumber = I('get.room_number') ? trim(I('get.room_number')) : '';
		if(!empty($roomnumber)){
			$where['orders.roomnumber'] = $roomnumber;
		}
		
		//账单日期
		$costlog_times = I('get.qorder_type', '');
		$costlog_years = I('get.qorder_year', date('Y'));
		if(!empty($costlog_times)){
			$where['orders.month'] = $costlog_years .'-'. str_pad($costlog_times, 2, '0', STR_PAD_LEFT);
		}
		
		//账单类型
		$order_type = I('get.order_type', 0);
		if(!empty($order_type)){
			$where['orders.order_type'] = $order_type;
		}
		//账单状态
		$status = I('get.status');
		if($status != '' && $status != 'all'){
			$where['orders.status'] = $status;
		}
		
		//获取列表
		$list = D('Costlog')->getCostLogAllList($where, 'orders.roomnumber/1 asc, orders.month asc');
		
		$xlsCell = array(
			array('id', '编号'),
			array('roomnumber','房间号'),
			array('btime','签约时间'),
			array('etime','截止时间'),
			array('eventtype_id','优惠编号'),
			array('member_nick','用户名'),
			array('order_type','类型'),
			array('month','收费月份'),
			array('rent','租金'),
			array('property','物业费'),
			array('rates1','水费'),
			array('rates2','电费'),
			array('other','其他'),
			array('begin_time','费用开始'),
			array('end_time','费用截止'),
			array('total','总金额'),
			array('discount','优惠金额'),
			array('account','应缴金额'),
			array('status','账单状态'),
			array('cjcount', '催缴次数'),
			array('cjtime', '催缴时间')
		);

		if(is_array($list)){
			foreach($list as $k=>$ls){
				$ls['id'] = $k+1;
				$ls['btime'] = date('Y-m-d', $ls['btime']);
				$ls['etime'] = date('Y-m-d', $ls['etime']);
				$ls['order_type'] = $ls['order_type'] == 1 ? '固定费用' : '日常费用';
				$ls['begin_time'] = date('Y-m-d', $ls['begin_time']);
				$ls['end_time'] = date('Y-m-d', $ls['end_time']);
				switch($ls['status']){
					case -1:
						$ls['status'] = '未审核';
					break;
					case 0:
						$ls['status'] = '未缴费';
					break;
					case 1:
						$ls['status'] = '已缴费';
					break;
					case 2:
						$ls['status'] = '无效';
					break;
				}

				$ls['cjtime'] = empty($ls['cjtime']) ? '' : date('Y-m-d', $ls['cjtime']);
				$excelData[] = $ls;
			}
		}
		//导出账单
		D('Excel')->exportExcelCostOrder('账单列表', $xlsCell, $excelData, '账单_'.date('Y-m-d H:i'));
		//echo 1;
	}
	
	/**
	 * 计算2个时间相差的月数
	 * @param time $date1 时间1
	 * @param time $data2 时间2
	 * 2018-01-17 ~ 2017-03-17
	 * 2017-03-17 ~ 2018-01-01
	 **/
	private function getMonthNum( $date1, $date2, $tags='-' ){
	 	$date1 = explode($tags,$date1);
	 	$date2 = explode($tags,$date2);
		if ($date1[0] >= $date2[0]){
			if($date1[1] >= $date2[1]){
				return abs($date1[0] - $date2[0]) * 12 + abs($date1[1] - $date2[1]);
			}else{
				return abs($date1[0] - $date2[0]) * 12 - abs($date1[1] - $date2[1]);
			}
		}else{
			if($date1[1] >= $date2[1]){
				return abs($date2[0] - $date1[0]) * 12 - abs($date1[1] - $date2[1]);
			}else{
				return abs($date2[0] - $date1[0]) * 12 + abs($date1[1] - $date2[1]);
			}
		}
		//return abs($date1[0]-$date2[0])*12 + $date1[1] - $date2[1]; 
	}
}
